package top.carrotguo.weibo.utils;

import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {

    public static boolean copyFile(File oldFile, File newFile){
        if (!oldFile.exists()) {
            Logger.e("复制的源文件不存在");
            return false;
        }
        if (oldFile.isDirectory()) {
            Logger.e("复制的文件是文件夹，无效");
            return false;
        }
        if (!oldFile.canRead()) {
            Logger.e("复制的文件不可读");
            return false;
        }
        File parent = newFile.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }

        if (!newFile.exists()) {
            try {
                newFile.createNewFile();
            } catch (IOException e) {
                Logger.e("创建新文件失败");
                e.printStackTrace();
            }
        }

        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(oldFile);
            fileOutputStream = new FileOutputStream(newFile);
            byte[] buffer= new byte[1024];
            int byteRead;
            while ((byteRead=fileInputStream.read(buffer))!=-1) {
                fileOutputStream.write(buffer,0,byteRead);
            }
            fileOutputStream.flush();
        } catch (FileNotFoundException e) {
            Logger.e("文件不存在");
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            Logger.e("io出错");
            e.printStackTrace();
            return false;
        }finally {
            IOUtils.close(fileOutputStream);
            IOUtils.close(fileInputStream);
        }
        return true;
    }
}
